/** * @file ifChild.html * @description 子窗口 */

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn1">发送消息</button>
    <script>
      const btn1 = document.getElementById("btn1");
      btn1.addEventListener("click", function () {
        console.log("btn1 child clicked");
        window.parent.postMessage("hello", "*");
      });
      window.onmessage = function (e) {
        console.log("orgin", e.origin);

        console.log("message from parent:", e.data);
        if (typeof e.data === "string") {
          const p = document.createElement("p");
          p.innerText = e.data;
          document.body.appendChild(p);
        }
      };
    </script>
  </body>
</html>
